package cn.virens.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.alibaba.fastjson.support.spring.FastjsonSockJsMessageCodec;

import cn.virens.web.components.websocket.WebSocketHandler;
import cn.virens.web.components.websocket.WebSocketHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class SpringWebSocketConfig implements WebSocketConfigurer {
	private WebSocketHandler mWebSocketHandler;
	private FastjsonSockJsMessageCodec mFastjsonSockJsMessageCodec;
	private WebSocketHandshakeInterceptor mWebSocketHandshakeInterceptor;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(webSocketHandler(), "/socket").addInterceptors(webSocketHandshakeInterceptor()).setAllowedOrigins("*");
		registry.addHandler(webSocketHandler(), "/socket/socketjs").addInterceptors(webSocketHandshakeInterceptor()).setAllowedOrigins("*").withSockJS().setMessageCodec(fastjsonSockJsMessageCodec());
	}

	@Bean
	public FastjsonSockJsMessageCodec fastjsonSockJsMessageCodec() {
		if (mFastjsonSockJsMessageCodec == null) {
			mFastjsonSockJsMessageCodec = new FastjsonSockJsMessageCodec();
		}

		return mFastjsonSockJsMessageCodec;
	}

	@Bean
	public WebSocketHandler webSocketHandler() {
		if (mWebSocketHandler == null) {
			mWebSocketHandler = new WebSocketHandler();
		}
		return mWebSocketHandler;
	}

	@Bean
	public WebSocketHandshakeInterceptor webSocketHandshakeInterceptor() {
		if (mWebSocketHandshakeInterceptor == null) {
			mWebSocketHandshakeInterceptor = new WebSocketHandshakeInterceptor();
		}

		return mWebSocketHandshakeInterceptor;
	}
}
